package com.lagou.rabbitmq.service;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lagou.rabbitmq.entity.OrderEntity;
import com.lagou.rabbitmq.entity.OrderEntity.OrderStatus;
import com.lagou.rabbitmq.mapper.OrderMapper;
import java.util.List;
import org.apache.commons.lang3.RandomStringUtils;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

@Service
@Transactional(rollbackFor = Exception.class)
public class OrderService extends ServiceImpl<OrderMapper, OrderEntity> {

    @Autowired
    private AmqpTemplate rabbitTemplate;

    public List<OrderEntity> cancelOrders(){
        return this.lambdaQuery().eq(OrderEntity::getStatus,OrderStatus.CANCLED).list();
    }

    public String order() {

        OrderEntity o = OrderEntity.builder()
            .orderNumber(RandomStringUtils.randomAlphabetic(10))
            .status(OrderStatus.UNPAID).build();
        this.save(o);

        rabbitTemplate.convertAndSend("ex.dir.order", "order", o.getId());
        return o.getOrderNumber();
    }

    public boolean pay(String orderNumber) {
        OrderEntity orderEntity = this.lambdaQuery().eq(OrderEntity::getOrderNumber, orderNumber).one();
        if (OrderStatus.CANCLED == orderEntity.getStatus()){
            return false;
        }
        orderEntity.setStatus(OrderStatus.PAID);
        this.updateById(orderEntity);
        return true;
    }

    @RabbitListener(queues = "queue.order.dlx")
    public void invalidOrder(Long orderId) {
        OrderEntity orderEntity = this.getById(orderId);
        if (OrderStatus.UNPAID == orderEntity.getStatus()){
            orderEntity.setStatus(OrderStatus.CANCLED);
            this.updateById(orderEntity);
        }
    }

}
